const { includes } = require("lodash");
const { getPageParams } = require("./page");
const { getParamsFromData } = require("./utils");
const User = require("../db/models/user");
const Article = require("../db/models/article");

// 文章分页查询
module.exports.getArticlesByPage = async (req, res, next) => {
  console.log("req.query.pageSize:", req.query.pageSize);

  //   const uid = 16;
  //   传过来的是字符串,需要自己处理成数字类型的,比如limit 之类的
  const { pageSize, pageIndex } = req.query;

  //  条件查询
  const where = getParamsFromData(req.query, "pageSize", "pageIndex");

  //   分页查询
  const pageParams = getPageParams({ pageSize, pageIndex });
  console.log("pageParams:", pageParams);
  let ret = await Promise.all([
    Article.findAll({
      ...pageParams,
      where,
      required: true,
      include: [
        {
          model: User,
          attributes: ["username", "nickname", "avatar", "id"],
        },
      ],
    }),
    Article.count({
      where,
    }),
  ]);
  console.log("ret[0]", ret[0]);
  //   delete ret[1].dataValues.id;
  //   delete ret[1].dataValues.pwd;
  const list =
    ret[0]?.map((article) => ({
      ...article.dataValues,
      ...ret[1].dataValues,
    })) || [];
  res.send({
    code: 200,
    data: {
      list,
      total: ret[1],
      current: +pageIndex,
      size: +pageSize,
    },
  });
};
